<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Admin\SmsClient;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\User as UserMode;

class User extends Controller
{
    //
    public function sendSms(Request $request)
    {
        $params = $request->except(['s']);
        $code = mt_rand(1000,9999);
        $result = (new SmsClient())->sendSmsCode($params['mobile'],$code);
        if($result['status']==200){
          DB::table('codes')->insertGetId(['mobile'=>$params['mobile'],'code'=>$code]);
        }
        return response()->json($result);
    }

    //注册手机号
    public function register(Request $request)
    {
        $params = $request->except(['s']);
        $mobile = $params['mobile'];
        $code = $params['code'];
        $user = DB::table('user')->where('mobile',$mobile)->first();
        if($user){
            return response()->json(['status'=>201,'msg'=>'该手机号已注册']);
        }else{
            $codes = DB::table('codes')->where('mobile',$mobile)->orderByDesc('id')->first();
            if($codes && $codes->code==$code){
                 $state = DB::table('user')->insertGetId(['mobile'=>$mobile]);
                 if($state){
                     return response()->json(['status'=>200,'msg'=>'手机号注册成功']);
                 }else{
                     return response()->json(['status'=>201,'msg'=>'手机号注册失败']);
                 }
            }else{
                return response()->json(['status'=>201,'msg'=>'验证码不正确']);
            }
        }
    }

    //登录
    public function login(Request $request)
    {
        $params = $request->except(['s']);
        $mobile = $params['mobile'];
        $code = $params['code'];
        $user = DB::table('user')->where('mobile',$mobile)->first();
        if(!$user){
            return response()->json(['status'=>201,'msg'=>'该手机号未注册']);
        }
        $codes = DB::table('codes')->where('mobile',$mobile)->orderByDesc('id')->first();
        if($codes && $codes->code==$code){
            $token = (Token::getInstance())->createToken($user->id);
            $state = DB::table('user')->where('mobile',$mobile)->update(['token'=>$token]);
            if($state){
                return response()->json(['status'=>200,'msg'=>'登录成功','data'=>['mobile'=>$mobile,'token'=>$token]]);
            }else{
                return response()->json(['status'=>201,'msg'=>'登录失败']);
            }
        }else{
            return response()->json(['status'=>201,'msg'=>'验证码不正确']);
        }
    }

}
